//
//  NetworkTools.swift
//  sinaweibo
//
//  Created by mac on 15/11/17.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking

private let weiboDomain = "com.baidu.data.error"

enum HTTPMethod: String {
    case GET = "GET"
    case POST = "POST"
    
}

class NetworkTools: AFHTTPSessionManager {
    
    //定义单例对象
    static let sharedTools:NetworkTools = {
        let urlString = "https://api.weibo.com/"
        let url = NSURL(string: urlString)
        let tools = NetworkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    //定义网络访问方法 以后的所有网络访问都会经过此方法/ 相当于添加一个"网络访问处理层"
    
    //加载字典数据
    func requestJsonDict(method:HTTPMethod ,urlString: String, parameters: [String:AnyObject]?, finished: (result : [String:AnyObject]?, error: NSError?) -> ()) {
        
        if method == HTTPMethod.GET {
            GET(urlString, parameters: parameters, success: { (_, result) -> Void in
                //判断加载的数据是否是字典的形式 是,回调成功
                if let dict = result as? [String: AnyObject]{
                    
                    finished(result: dict, error: nil)
                    return
                }
                
                //如果返回的数据格式不匹配,自定义错误信息
                //domain 代表域名的反转
                let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据错误"])
                finished(result: nil, error: dataError)
                }) { (_, error) -> Void in
                    finished(result: nil, error: error)
                    print(error)
            }
            
        }else{
            POST(urlString, parameters: parameters, success: { (_, result) -> Void in
                //判断加载的数据是否是字典的形式 是,回调成功
                if let dict = result as? [String: AnyObject]{
                    
                    finished(result: dict, error: nil)
                    return
                }
                
                //如果返回的数据格式不匹配,自定义错误信息
                //domain 代表域名的反转
                let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据错误"])
                
                finished(result: nil, error: dataError)
                }) { (_, error) -> Void in
                    finished(result: nil, error: error)
                    print(error)
            }
        }
    }   
}
